/**
 * 由一个父进程fork出两个子进程(进程扇)进行数据传递
*/

#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{

    int pipe_fds[2];
    if (pipe(pipe_fds) < 0)
    {
        perror("pipe error: ");
        exit(EXIT_FAILURE);
    }

    int i = 1;
    for (; i <= 2; ++i)
    {
        pid_t pid = fork();
        if (0 > pid)
        {
            perror("fork error: ");
            exit(EXIT_FAILURE);
        }
        else if (0 == pid)
        {
            if (1 == i)
            {
                close(pipe_fds[0]);
                write(pipe_fds[1], "123", 3);
                printf("[%u] write [%s]\n", getpid(), "123");
                close(pipe_fds[1]);
            }
            else if (2 == i)
            {
                close(pipe_fds[1]);
                char buf[4] = {0};
                read(pipe_fds[0], buf, 4);
                printf("[%u] read [%s]\n", getpid(), buf);
                close(pipe_fds[0]);
            }
            exit(EXIT_SUCCESS);
        }
        else
        {
            if (2 == i)
            {
                wait(0);
                wait(0);

                printf("退出主进程，关闭管道。。\n");

                close(pipe_fds[0]);
                close(pipe_fds[1]);
            }
        }
    }

    return 0;
}